package cn.yj.lock.aqs;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.locks.AbstractOwnableSynchronizer;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.LockSupport;

/**
 * @author 永健
 * @since 2022-02-24 14：52
 */
public abstract class AbstractAqs extends AbstractOwnableSynchronizer {
    private transient volatile Node head;

    private transient volatile Node tail;

    private volatile int state;

    static final class Node {
        // 独占锁
        static final Node EXCLUSIVE = null;

        /**
         * 当前获取锁的资源放弃获取锁
         */
        static final int CANCELLED = 1;

        // 正常等待拿锁：是独占锁的时候所有在队列中的正常等待的线程都是这个状态
        static final int SIGNAL = -1;
        static final int CONDITION = -2;
        static final int PROPAGATE = -3;

        // 负值表示结点处于有效等待状态
        volatile int waitStatus;

        // 当前节点的前继节点
        volatile Node prev;

        // 当前节点的后继节点
        volatile Node next;

        // 等待被唤醒的节点
        Node nextWaiter;

        // 来取锁的线程
        volatile Thread thread;


        public Node(Thread thread, Node model) {
            this.thread = thread;
            this.nextWaiter = model;
        }

        public Node() {
        }

        /**
         * 获取前驱节点
         *
         * @throws NullPointerException
         */
        final Node predecessor() throws NullPointerException {
            Node p = prev;
            if (p == null) {
                throw new NullPointerException();
            }
            return p;
        }
    }


    public AbstractAqs() {
    }

    public final void acquire(int arg) {
        if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) {
            selfInterrupt();
        }
        System.out.println(Thread.currentThread().getName() + "不阻塞");
    }

    /**
     * 获取锁失败后，将节点，放到队列的尾部
     *
     * @param mode
     */
    private final Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        System.out.println(Thread.currentThread().getName() + "：包装成节点进入队尾");
        // 判断尾部节点是不是为空
        Node pre = tail;
        if (pre != null) {
            // 新的节点作为尾部节点，那新节点的前继节点就是之前的尾部节点
            node.prev = pre;
            // cas更新尾部节点
            if (compareAndSetTail(pre, node)) {
                // 旧的尾部节点指向新的尾部节点

                return node;
            }
        }
        enq(node);
        return node;
        // 自旋

    }

    private Node enq(final Node node) {
        for (; ; ) {
            Node t = tail;
            // 尾部节点为空- 队列为空，自己是第一个来抢锁的
            if (t == null) {
                System.out.println(Thread.currentThread().getName() + "：第一个进来排队的节点");
                // cas 创建一个空的头节点，收尾都是它自己
                if (compareAndSetHead(new Node())) {
                    tail = head;
                }
            } else {
                node.prev = t;
                // 将自己加入尾部节点
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    System.out.println(Thread.currentThread().getName() + "：加入队列尾部");
                    return t;
                }
            }
        }
    }


    public final boolean hasQueuedPredecessors() {
        Node t = tail; // Read fields in reverse initialization order
        Node h = head;
        Node s;
        return h != t &&
                ((s = h.next) == null || s.thread != Thread.currentThread());
    }

    /**
     * 再次获取锁，不符合条件或者获取锁失败后进进入waiting了
     *
     * @param node
     * @param state
     */
    private final boolean acquireQueued(final Node node, int state) {
        System.out.println(Thread.currentThread().getName() + "：先自旋拿锁一次");
        // 标记是否成功拿失败锁
        boolean failed = true;
        // 是否被中段过
        boolean interrupted = false;
        try {
            for (; ; ) {
                // 前节点
                final Node p = node.predecessor();

                // 当前节点的前继节是头节点，那说明队列里面的下一个要获取锁资源的就是自己了
                // 所以尝会一直自旋获取锁资源。如果不是就休眠吧
                System.out.println(Thread.currentThread().getName() + "：自旋拿锁");
                boolean acquire = tryAcquire(state);
                System.out.println(Thread.currentThread().getName() + (acquire? "：自旋尝试拿锁成功" : "：自旋尝试拿锁失败！"));
                System.out.println(Thread.currentThread().getName() + ":上一个节点线程： acquire=" + acquire + ",p==head:" + (p == head));
                if (p == head && acquire) {
                    setHead(node);
                    // 将后继节点指向空
                    p.next = null;
                    failed = false;
                    return interrupted;
                }
                // waiting判断，过滤不可用的节点线程
                if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) {
                    interrupted = true;
                }
            }
        } finally {
            if (failed) {

            }
        }
    }


    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;

        System.out.println(Thread.currentThread().getName() + "：waiting判断，过滤不可用的节点线程");
        // 前继节点在等待中获取锁中，还没有到自己，符合waiting条件
        if (ws == Node.SIGNAL) {
            System.out.println(Thread.currentThread().getName() + "：前置节持有锁中,waitingStatus=" + Node.SIGNAL);
            return true;
        }

        // CANCELLED = 1; 就是大于0，代表了当前线程放弃了获取锁
        if (ws > 0) {
            //例如：A-B-C-D-F,此时D是当前线程,它的前继节点C的状态为1，已被取消调度，所以此时在C这里往前找，C.pre.waitingStatus是否<=0,直到找到为止，然后就会跳过C这个节点，c.pre
            // 为B,B.next = D。这样子就跳过了，然后将其D的前继节点的waitingStatus 通过cas操作将其改为 -1。 此时条件满足线程waiting,D继续进入休眠等待唤醒。
            do {
                // 继续往前找可用的节点
                node.prev = pred = pred.prev;
            }
            while (pred.waitStatus > 0);

            // 将自己插队到正常在等待的节点后面
            pred.next = node;
        } else {
            // 前驱节点正常，就将前驱节点的状态改为 SIGNAL，
            // 前驱节点正在等待获取锁，所以acquireQueued在一次循环的时候，前驱节点还没有拿到锁，当前节点就可以休眠了interrupt
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
            System.out.println(Thread.currentThread().getName() + "：cas 修改前置节点的waitingStatus=-1");
        }
        return false;
    }


    public final boolean release(int arg) {
        System.out.println(Thread.currentThread().getName() + "： 释放锁");
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0) {
                unparkSuccessor(h);
            }
            return true;
        }
        return false;
    }

    private void unparkSuccessor(Node node) {

        int ws = node.waitStatus;
        if (ws < 0) {
            compareAndSetWaitStatus(node, ws, 0);
        }

        Node s = node.next;
        if (s == null || s.waitStatus > 0) {
            s = null;
            // 从后向前找。
            for (Node t = tail; t != null && t != node; t = t.prev) {
                // 找到最前面正常等待那个
                if (t.waitStatus <= 0) {
                    s = t;
                }
            }
        }
        if (s != null) {
            LockSupport.unpark(s.thread);
            System.out.println("该线程：" + s.thread.getName() + " 被唤醒");
        }
    }


    private final boolean parkAndCheckInterrupt() {
        System.out.println(Thread.currentThread().getName() + "：线程park，进入 waiting状态等待被唤醒");
        LockSupport.park(this);

        // 模拟线程中断
        //        if (Thread.currentThread().getName().equals("Thread-1")){
        //            Thread.currentThread().interrupt();
        //        }

        boolean interrupted = Thread.interrupted();
        System.out.println(Thread.currentThread().getName() + "：线程park结束，被唤醒。是否被中断：" + interrupted);
        System.out.println(Thread.currentThread().getName() + "：尝试重新获取锁...");
        return interrupted;
    }


    private void setHead(Node node) {
        this.head = node;
    }

    static void selfInterrupt() {
        Thread.currentThread().interrupt();
    }

    public int getState() {
        return state;
    }

    public AbstractAqs setState(int state) {
        this.state = state;
        return this;
    }

    private static final Unsafe unsafe;
    private static final long stateOffset;
    private static final long headOffset;
    private static final long tailOffset;
    private static final long waitStatusOffset;
    private static final long nextOffset;

    static {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
            stateOffset = unsafe.objectFieldOffset(AbstractAqs.class.getDeclaredField("state"));
            headOffset = unsafe.objectFieldOffset(AbstractAqs.class.getDeclaredField("head"));
            tailOffset = unsafe.objectFieldOffset(AbstractAqs.class.getDeclaredField("tail"));
            waitStatusOffset = unsafe.objectFieldOffset(Node.class.getDeclaredField("waitStatus"));
            nextOffset = unsafe.objectFieldOffset(Node.class.getDeclaredField("next"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    protected final boolean compareAndSetState(int expect, int update) {
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }

    protected final boolean compareAndSetTail(Node expect, Node update) {
        return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
    }

    protected final boolean compareAndSetHead(Node update) {
        return unsafe.compareAndSwapObject(this, headOffset, null, update);
    }

    protected static final boolean compareAndSetWaitStatus(
            Node node, int expect, int update) {
        return unsafe.compareAndSwapInt(node, waitStatusOffset, expect, update);
    }

    private static final boolean compareAndSetNext(
            Node node, Node expect, Node update) {
        return unsafe.compareAndSwapObject(node, nextOffset, expect, update);
    }

    protected abstract boolean tryAcquire(int state);

    protected abstract boolean tryRelease(int arg);

}
